<template>
	<el-tabs v-model="data.activeTab" class="demo-tabs" @tab-click="handleClickTab">
		<el-tab-pane label="终端充电告警" name="terminal">
			<Table v-if="data.activeTab === 'terminal'" ref="tableRef" @get-list="getList" :columns="data.columns"
				:query="data.query" :toolbar="data.toolbar"></Table>
		</el-tab-pane>
		<el-tab-pane label="电桩离线告警" name="plie">
			<Table v-if="data.activeTab === 'plie'" ref="tablePlieRef" @get-list="getPlieList"
				:columns="plieData.columns" :query="plieData.query" :toolbar="plieData.toolbar"></Table>
		</el-tab-pane>
		<el-tab-pane label="电桩故障告警" name="fault">
			<Table v-if="data.activeTab === 'fault'" ref="tableFaultRef" @get-list="getFaultList"
				:columns="faultData.columns" :query="faultData.query" :toolbar="faultData.toolbar"></Table>
		</el-tab-pane>
	</el-tabs>
</template>

<script lang="ts" setup name="pileSafetyAlarmList">
	import Table from '@/components/table/index.vue';
	import { queryDicByParent } from '@/service/apis/api';
	import { getCity, exportFile, findKeyByValue } from '@/utils/utils';
	import {
		getChargeAlarmPage,
		EXPORT_CHARGEALARMPAGE,
		getOfflineAlarmPage,
		EXPORT_OFFLINEALARMPAGE,
		getFaultAlarmPage,
		URL_GETFAULTPAGE,
		EXPORT_FAULTPAGE,
	} from '@/service/apis/alarm';
	import { equipmentBrandAndModelTreeData } from '@/service/apis/pile';
	import { TRUE_FALSE, ALARM_LEVEL } from '@/utils/dictionaries';
	import moment from 'moment';

	const router = useRouter();

	const tableRef = ref();
	const tablePlieRef = ref();
	const tableFaultRef = ref();

	//获取品牌型号数据
	equipmentBrandAndModelTreeData({}).then((res : any) => {
		if (res) {
			data.query[2].props.options = [...res];
			plieData.query[3].props.options = [...res];
			faultData.query[2].props.options = [...res];
		}
	});
	// 获取省市
	getCity().then((res : any) => {
		plieData.query[8].props.options = [...res];
		faultData.query[8].props.options = [...res];
	});

	const brandModel = (item : any) => {
		if (item.equipmentBrandName && item.equipmentModelName) {
			return `${item.equipmentBrandName}/${item.equipmentModelName}`;
		}
		return '--';
	};

	const data = reactive({
		pickDate: null as any,
		activeTab: 'terminal',
		connectorWorkStatus: [] as any,
		connectorWorkStatusType: [] as any,
		alarmTermTypeData: [] as any,
		columns: [
			{
				prop: 'connectorName',
				label: '终端名称',
				width: 160,
			},
			{
				prop: 'connectorCode',
				label: '终端编码',
				width: 160,
			},
			{
				prop: 'stationName',
				label: '归属电站',
				width: 160,
			},
			{
				prop: 'equipmentBrand',
				label: '品牌型号',
				width: 160,
				template: (row : any) => {
					return brandModel(row);
				},
			},
			{
				prop: 'startChargeSeq',
				label: '充电订单',
				width: 160,
			},
			{
				prop: 'alarmLevel',
				label: '告警等级',
				width: 120,
			},
			{
				prop: 'alarmTime',
				label: '告警时间',
				width: 140,
			},
			{
				prop: 'notify',
				label: '是否短信通知',
				width: 120,
				template: (row : any, index : number) => {
					return row.notify ? '是' : '否';
				},
			},
			{
				prop: 'stop',
				label: '是否停充',
				width: 160,
				template: (row : any, index : number) => {
					return row.stop ? '是' : '否';
				},
			},
			{
				prop: 'chargeAlarmType',
				label: '告警原因',
				width: 160,
				template: (row : any) => {
					const chargeAlarm = findKeyByValue(
						data.alarmTermTypeData,
						row.chargeAlarmType
					);
					return `[${chargeAlarm}]${row.alarmValue}/${row.alarmThreshold}`;
				},
			},
		],
		toolbar: [
			{
				label: '导出',
				permission: 'pileSafetyAlarmList.export',
				icon: 'icon-export',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					const startData = tableRef?.value.getForm().alarmStartTime;
					const startData1 = tableRef?.value.getForm().alarmEndTime;
					const day = moment(startData1).diff(moment(startData), 'day');
					if ((startData || day > 0) && day < 63) {
						exportFile(
							EXPORT_CHARGEALARMPAGE,
							'终端充电告警记录',
							tableRef.value?.getForm()
						);
					} else {
						ElMessageBox.alert(
							'单次导出最多支持导出周期为2个月的数据，请按时间筛选导出对象后再导出。',
							'提示',
							{
								confirmButtonText: '确认',
								type: 'warning',
							}
						);
					}
				},
			},
		],
		query: [
			{
				label: '终端编码',
				prop: 'connectorCode',
				comName: 'input',
				props: {
					placeholder: '请输入终端编码',
				},
			},
			{
				label: '归属电站',
				prop: 'stationName',
				comName: 'input',
				props: {
					placeholder: '请输入归属电站',
				},
			},
			{
				label: '品牌型号',
				prop: 'equipmentBrandModel',
				comName: 'cascader',
				props: {
					placeholder: '请选择品牌型号',
					props: {
						checkStrictly: true,
					},
					options: [] as any,
				},
			},
			{
				label: '告警原因',
				prop: 'chargeAlarmType',
				comName: 'select',
				props: {
					placeholder: '请选择告警原因',
					options: [] as any,
				},
			},
			{
				label: '告警等级',
				prop: 'alarmLevel',
				comName: 'select',
				props: {
					placeholder: '请选择告警等级',
					options: ALARM_LEVEL,
				},
			},
			{
				label: '是否停充',
				prop: 'isStopCharging',
				comName: 'select',
				props: {
					placeholder: '请选择是否停充',
					options: TRUE_FALSE,
				},
			},
			{
				label: '告警时间',
				prop: 'alarmTime',
				comName: 'date',
				keys: ['alarmStartTime', 'alarmEndTime'],
				props: {
					type: 'daterange',
					calendarChange: (pick : any) => {
						let hasSelectDate = pick !== null && pick.length > 0;
						data.pickDate = hasSelectDate ? pick[0] : null;
					},
					change: (time : any) => {
						if (!time) {
							data.pickDate = null;
						}
					},
					disabledDate: (time : any) : any => {
						if (data.pickDate) {
							const checkTime = data.pickDate.getTime();
							const startTime = checkTime - 62 * 86400 * 1000; // 前面限制62天
							const endTime = checkTime + 62 * 86400 * 1000; // 后面限制62天
							return time.getTime() > endTime || time.getTime() < startTime;
						} else {
							return false;
						}
					},
				},
			},
		],
	});
	const plieData = reactive({
		columns: [
			{
				prop: 'equipmentName',
				label: '电桩名称',
				width: 160,
			},
			{
				prop: 'equipmentCode',
				label: '电桩编码',
				width: 160,
			},
			{
				prop: 'stationName',
				label: '归属电站',
				width: 160,
			},
			{
				prop: 'operatorName',
				label: '运营商',
				width: 160,
			},
			{
				prop: 'equipmentBrand',
				label: '品牌型号',
				template: (row : any, index : any) => {
					return brandModel(row);
				},
				width: 160,
			},
			{
				prop: 'occurTime',
				label: '离线发生时间',
				width: 150,
			},
			{
				prop: 'beforeStatus',
				label: '异常变位状态',
				width: 160,
				template: (row : any) => {
					const beforeStatus = findKeyByValue(
						data.connectorWorkStatus,
						row.beforeStatus
					);
					const currentStatus = findKeyByValue(
						data.connectorWorkStatus,
						row.currentStatus
					);
					return `${beforeStatus}->${currentStatus}`;
				},
			},
			{
				prop: 'recoveryTime',
				label: '离线恢复时间',
				width: 150,
			},
			{
				prop: 'alarmStatus',
				label: '异常状态',
				dic: [] as any,
				type: Number,
			},
			{
				prop: 'duration',
				label: '离线时长（分钟）',
				width: 140,
				template: (row : any) => {
					if (row.duration == 0) {
						return String(row.duration);
					} else if (row.duration) {
						return row.duration;
					} else {
						return '--';
					}
				},
			},
		],
		query: [
			{
				label: '离线发生时间',
				prop: 'occurTime',
				comName: 'date',
				keys: ['occurStartTime', 'occurEndTime'],
				props: {
					type: 'daterange',
					calendarChange: (pick : any) => {
						let hasSelectDate = pick !== null && pick.length > 0;
						data.pickDate = hasSelectDate ? pick[0] : null;
					},
					change: (time : any) => {
						if (!time) {
							data.pickDate = null;
						}
					},
					disabledDate: (time : any) : any => {
						if (data.pickDate) {
							const checkTime = data.pickDate.getTime();
							const startTime = checkTime - 62 * 86400 * 1000; // 前面限制62天
							const endTime = checkTime + 62 * 86400 * 1000; // 后面限制62天
							return time.getTime() > endTime || time.getTime() < startTime;
						} else {
							return false;
						}
					},
				},
			},
			{
				label: '电桩编码',
				prop: 'equipmentCode',
				comName: 'input',
				props: {
					placeholder: '请输入电桩编码',
				},
			},
			{
				label: '归属电站',
				prop: 'stationName',
				comName: 'input',
				props: {
					placeholder: '请输入归属电站',
				},
			},
			// {
			//   label: '品牌型号',
			//   prop: 'equipmentModel',
			//   comName: 'input',
			//   props: {
			//     placeholder: '请输入品牌型号',
			//   },
			// },
			{
				label: '品牌型号',
				prop: 'equipmentBrandModel',
				comName: 'cascader',
				props: {
					placeholder: '请选择品牌型号',
					props: {
						checkStrictly: true,
					},
					options: [] as any,
				},
			},
			{
				label: '离线恢复时间',
				prop: 'recoveryData',
				comName: 'date',
				keys: ['recoveryStartTime', 'recoveryEndTime'],
				props: {
					type: 'daterange',
					calendarChange: (pick : any) => {
						let hasSelectDate = pick !== null && pick.length > 0;
						data.pickDate = hasSelectDate ? pick[0] : null;
					},
					change: (time : any) => {
						if (!time) {
							data.pickDate = null;
						}
					},
					disabledDate: (time : any) : any => {
						if (data.pickDate) {
							const checkTime = data.pickDate.getTime();
							const startTime = checkTime - 62 * 86400 * 1000; // 前面限制62天
							const endTime = checkTime + 62 * 86400 * 1000; // 后面限制62天
							return time.getTime() > endTime || time.getTime() < startTime;
						} else {
							return false;
						}
					},
				},
			},
			{
				label: '离线时长',
				prop: 'durationStart',
				comName: 'input',
				props: {
					placeholder: '≥输入值',
					type: 'number',
				},
			},
			{
				label: '离线时长',
				prop: 'durationEnd',
				comName: 'input',
				props: {
					placeholder: '≤输入值',
					type: 'number',
				},
			},
			{
				label: '异常状态',
				prop: 'alarmStatus',
				comName: 'select',
				props: {
					placeholder: '请选择异常状态',
					options: [] as any,
				},
			},
			{
				label: '离线电桩城市',
				prop: 'citys',
				comName: 'cascader',
				props: {
					placeholder: '请选择电桩城市',
					options: [] as any,
				},
			},
		],
		toolbar: [
			{
				label: '导出',
				permission: 'pileSafetyAlarmList.export',
				icon: 'icon-export',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					const startData = tablePlieRef?.value.getForm().occurStartTime;
					const startData1 = tablePlieRef?.value.getForm().occurEndTime;
					const recoveryStartTime =
						tablePlieRef?.value.getForm().recoveryStartTime;
					const recoveryEndTime = tablePlieRef?.value.getForm().recoveryEndTime;
					const day = moment(startData1).diff(moment(startData), 'day');
					const day1 = moment(recoveryEndTime).diff(
						moment(recoveryStartTime),
						'day'
					);
					if (
						((startData || day > 0) && day < 63) ||
						((recoveryStartTime || day1 > 0) && day1 < 63)
					) {
						exportFile(
							EXPORT_OFFLINEALARMPAGE,
							'电桩离线告警记录',
							tablePlieRef.value?.getForm()
						);
					} else {
						ElMessageBox.alert(
							'单次导出最多支持导出周期为2个月的数据，请按时间筛选导出对象后再导出。',
							'提示',
							{
								confirmButtonText: '确认',
								type: 'warning',
							}
						);
					}
				},
			},
		],
	});
	const faultData = reactive({
		columns: [
			{
				prop: 'connectorName',
				label: '终端名称',
				width: 160,
			},
			{
				prop: 'connectorCode',
				label: '终端编码',
				width: 160,
			},
			{
				prop: 'stationName',
				label: '归属电站',
				width: 160,
			},
			{
				prop: 'equipmentBrand',
				label: '品牌型号',
				template: (row : any) => {
					return brandModel(row);
				},
			},
			{
				prop: 'occurTime',
				label: '告警时间',
			},
			{
				prop: 'actualAmount',
				label: '变位状态',
				template: (row : any) => {
					const beforeStatus = findKeyByValue(
						data.connectorWorkStatus,
						row.beforeStatus
					);
					const currentStatus = findKeyByValue(
						data.connectorWorkStatus,
						row.currentStatus
					);
					return `${beforeStatus}->${currentStatus}`;
				},
			},
			{
				prop: 'alarmCode',
				label: '告警码',
			},
			{
				prop: 'alarmMsg',
				label: '告警事项',
			},
			{
				prop: 'recoveryTime',
				label: '告警恢复时间',
			},
		],
		toolbar: [
			{
				label: '导出',
				permission: 'pileSafetyAlarmList.export',
				icon: 'icon-export',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					const startData = tableFaultRef?.value.getForm().occurStartTime;
					const startData1 = tableFaultRef?.value.getForm().occurEndTime;
					const day = moment(startData1).diff(moment(startData), 'day');
					if ((startData || day > 0) && day < 63) {
						exportFile(
							EXPORT_FAULTPAGE,
							'电桩故障告警记录',
							tableFaultRef.value?.getForm()
						);
					} else {
						ElMessageBox.alert(
							'单次导出最多支持导出周期为2个月的数据，请按时间筛选导出对象后再导出。',
							'提示',
							{
								confirmButtonText: '确认',
								type: 'warning',
							}
						);
					}
				},
			},
		],
		query: [
			{
				label: '终端编码',
				prop: 'connectorCode',
				comName: 'input',
				props: {
					placeholder: '请输入终端编码',
				},
			},
			{
				label: '归属电站',
				prop: 'stationName',
				comName: 'input',
				props: {
					placeholder: '请输入归属电站',
				},
			},
			// {
			//   label: '品牌型号',
			//   prop: 'equipmentModel',
			//   comName: 'select',
			//   props: {
			//     placeholder: '请选择品牌型号',
			//     options: [] as any,
			//   },
			// },
			{
				label: '品牌型号',
				prop: 'equipmentBrandModel',
				comName: 'cascader',
				props: {
					placeholder: '请选择品牌型号',
					props: {
						checkStrictly: true,
					},
					options: [] as any,
				},
			},
			{
				label: '告警码',
				prop: 'alarmCode',
				comName: 'input',
				props: {
					placeholder: '请输入告警码',
				},
			},
			{
				label: '告警事项',
				prop: 'alarmMsg',
				comName: 'input',
				props: {
					placeholder: '请输入告警事项',
				},
			},
			{
				label: '告警时间',
				prop: 'occurData',
				comName: 'date',
				keys: ['occurStartTime', 'occurEndTime'],
				props: {
					type: 'daterange',
					calendarChange: (pick : any) => {
						let hasSelectDate = pick !== null && pick.length > 0;
						data.pickDate = hasSelectDate ? pick[0] : null;
					},
					change: (time : any) => {
						if (!time) {
							data.pickDate = null;
						}
					},
					disabledDate: (time : any) : any => {
						if (data.pickDate) {
							const checkTime = data.pickDate.getTime();
							const startTime = checkTime - 62 * 86400 * 1000; // 前面限制62天
							const endTime = checkTime + 62 * 86400 * 1000; // 后面限制62天
							return time.getTime() > endTime || time.getTime() < startTime;
						} else {
							return false;
						}
					},
				},
			},
			{
				label: '恢复时间',
				prop: 'recoveryData',
				comName: 'date',
				keys: ['recoveryStartTime', 'recoveryEndTime'],
				props: {
					type: 'daterange',
					calendarChange: (pick : any) => {
						let hasSelectDate = pick !== null && pick.length > 0;
						data.pickDate = hasSelectDate ? pick[0] : null;
					},
					change: (time : any) => {
						if (!time) {
							data.pickDate = null;
						}
					},
					disabledDate: (time : any) : any => {
						if (data.pickDate) {
							const checkTime = data.pickDate.getTime();
							const startTime = checkTime - 62 * 86400 * 1000; // 前面限制62天
							const endTime = checkTime + 62 * 86400 * 1000; // 后面限制62天
							return time.getTime() > endTime || time.getTime() < startTime;
						} else {
							return false;
						}
					},
				},
			},
			{
				label: '报警状态',
				prop: 'alarmStatus',
				comName: 'select',
				props: {
					placeholder: '请选择报警状态',
					options: [
						{ label: "报警", type: "alarmStatus", value: "0" },
						{ label: "恢复", type: "alarmStatus", value: "1" }] as any,
				},
			},
			{
				label: '电桩城市',
				prop: 'citys',
				comName: 'cascader',
				props: {
					placeholder: '请选择电桩城市',
					options: [] as any,
				},
			},
		],
	});

	queryDicByParent({
		listDtos: [
			'connectorWorkStatus',
			'OfflineAlarmStatus',
			'AlarmTermType',
			'ConnectorChargeAlarmType',
		],
	}).then((res : any) => {
		if (res) {
			data.connectorWorkStatusType = [...res.ConnectorChargeAlarmType];
			data.connectorWorkStatus = [...res.connectorWorkStatus];
			data.alarmTermTypeData = [...res.AlarmTermType];
			// data.query[2].props.options = [...res.equipmentModelType];
			data.query[3].props.options = [...res.ConnectorChargeAlarmType];
			plieData.query[7].props.options = [...res.OfflineAlarmStatus];
			plieData.columns[8].dic = [...res.OfflineAlarmStatus];
		}
	});

	const getList = (page : any, search : any) => {
		const form = search.ruleForm;
		delete form.equipmentBrand;
		delete form.equipmentModel;
		if (form.equipmentBrandModel?.length === 1) {
			form.equipmentBrand = form.equipmentBrandModel[0];
		}
		if (form.equipmentBrandModel?.length === 2) {
			form.equipmentBrand = form.equipmentBrandModel[0];
			form.equipmentModel = form.equipmentBrandModel[1];
		}
		if (form.alarmTime && form.alarmTime.length > 0) {
			form.alarmStartTime = form.alarmTime[0];
			form.alarmEndTime = form.alarmTime[1];
		} else {
			form.alarmStartTime = '';
			form.alarmEndTime = '';
		}
		getChargeAlarmPage(form, page).then((res : any) => {
			if (res) {
				if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
					page.pageNo--;
					getList(page, search);
					return;
				}
				nextTick(() => {
					tableRef.value.setTable({
						total: res.totalCount,
						table: res.dataList,
					});
				});
			}
		});
	};

	const getPlieList = (page : any, search : any) => {
		const form = search.ruleForm;
		delete form.equipmentBrand;
		delete form.equipmentModel;
		if (form.citys?.length > 0) {
			form.equipmentCode = form.citys[1].substring(0, 4);
		}
		if (form.equipmentBrandModel?.length === 1) {
			form.equipmentBrand = form.equipmentBrandModel[0];
		}
		if (form.equipmentBrandModel?.length === 2) {
			form.equipmentBrand = form.equipmentBrandModel[0];
			form.equipmentModel = form.equipmentBrandModel[1];
		}
		if (form.occurTime && form.occurTime.length > 0) {
			form.occurStartTime = form.occurTime[0];
			form.occurEndTime = form.occurTime[1];
		} else {
			form.occurStartTime = '';
			form.occurEndTime = '';
		}
		if (form.recoveryData && form.recoveryData.length > 0) {
			form.recoveryStartTime = form.recoveryData[0];
			form.recoveryEndTime = form.recoveryData[1];
		} else {
			form.recoveryStartTime = '';
			form.recoveryEndTime = '';
		}
		// if (form.durationData && form.durationData.length > 0) {
		//   form.durationStart = form.durationData[0];
		//   form.durationEnd = form.durationData[1];
		// } else {
		//   form.durationStart = '';
		//   form.durationEnd = '';
		// }
		getOfflineAlarmPage(form, page).then((res : any) => {
			if (res) {
				if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
					page.pageNo--;
					getPlieList(page, search);
					return;
				}
				nextTick(() => {
					tablePlieRef.value.setTable({
						total: res.totalCount,
						table: res.dataList,
					});
				});
			}
		});
	};

	const getFaultList = (page : any, search : any) => {
		const form = search.ruleForm;
		delete form.equipmentBrand;
		delete form.equipmentModel;
		if (form.citys?.length > 0) {
			form.connectorCode = form.citys[1].substring(0, 4);
		}
		if (form.equipmentBrandModel?.length === 1) {
			form.equipmentBrand = form.equipmentBrandModel[0];
		}
		if (form.equipmentBrandModel?.length === 2) {
			form.equipmentBrand = form.equipmentBrandModel[0];
			form.equipmentModel = form.equipmentBrandModel[1];
		}

		if (form.occurData && form.occurData.length > 0) {
			form.occurStartTime = form.occurData[0];
			form.occurEndTime = form.occurData[1];
		} else {
			form.occurStartTime = '';
			form.occurEndTime = '';
		}
		if (form.recoveryData && form.recoveryData.length > 0) {
			form.recoveryStartTime = form.recoveryData[0];
			form.recoveryEndTime = form.recoveryData[1];
		} else {
			form.recoveryStartTime = '';
			form.recoveryEndTime = '';
		}
		getFaultAlarmPage(form, page).then((res : any) => {
			if (res) {
				if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
					page.pageNo--;
					getFaultList(page, search);
					return;
				}
				nextTick(() => {
					tableFaultRef.value.setTable({
						total: res.totalCount,
						table: res.dataList,
					});
				});
			}
		});
	};

	const handleClickTab = (e : any) => { };
</script>